﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Sunny.UI;
using LogisticsAndong.Model;
using System.Threading;
using LogisticsAndong.Business;
using LogisticsAndong.Comm;
using LeederGlobal;
using LogisticsAndong.Handle;
using Leeder.Logger;

namespace LogisticsAndong.Forms
{
    public partial class FrmProgressDirection : UIPage
    {
        AutoSizeFormClass asc = new AutoSizeFormClass();

        /// <summary>
        /// 日志
        /// </summary>
        public LogOperate LogObj => Log.GetLogger(this.GetType());

        MaterialDirectionBLL bllMaterialDirection = new MaterialDirectionBLL();
        LogisticsAndongHandler logisticsAndongHandler;

        /// <summary>
        /// 开捆状态
        /// </summary>
        CancellationTokenSource cancel_KKStatuscontrol;

        FrmSystemSet frmSystemSet = new FrmSystemSet();

        /// <summary>
        /// 判断窗体是否首次加载
        /// </summary>
        bool isLoad = true;     

        public FrmProgressDirection()
        {
            InitializeComponent();

            //初始化服务
            logisticsAndongHandler = LogisticsAndongHandler.CreateInstance();
            logisticsAndongHandler.LipChangeEvent += sysjUiUpdate_event;
            logisticsAndongHandler.LsdChangeEvent += lsdUiUpdate_event;
            //dgvDateSet();
        }

        private void FrmProgressDirection_Load(object sender, EventArgs e)
        {
            //如果窗体已经加载过则不重新加载
            if (!isLoad)
            {
                DgvUpadte();
                return;
            }
            isLoad = false;

            //顺引顺建内制品
            dgvDMSY.AutoGenerateColumns = false;
            dgvDMSY.AllowUserToAddRows = false;
            dgvDMSY.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dgvDMSY.ReadOnly = true;
            dgvDMSY.AddColumn("序号", "ID", 10);
            dgvDMSY.AddColumn("工程名称", "MaterialName", 45);
            dgvDMSY.AddColumn("剩余台数", "LeftCount", 45);

            dgvXMSY.AutoGenerateColumns = false;
            dgvXMSY.AllowUserToAddRows = false;
            dgvXMSY.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dgvXMSY.ReadOnly = true;
            dgvXMSY.AddColumn("序号", "ID", 10);
            dgvXMSY.AddColumn("工程名称", "MaterialName", 45);
            dgvXMSY.AddColumn("剩余台数", "LeftCount", 45);

            dgvZWSJ.AutoGenerateColumns = false;
            dgvZWSJ.AllowUserToAddRows = false;
            dgvZWSJ.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dgvZWSJ.ReadOnly = true;
            dgvZWSJ.AddColumn("序号", "ID", 10);
            dgvZWSJ.AddColumn("工程名称", "MaterialName", 45);
            dgvZWSJ.AddColumn("剩余台数", "LeftCount", 45);

            dgvNZP.AutoGenerateColumns = false;
            dgvNZP.AllowUserToAddRows = false;
            dgvNZP.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dgvNZP.ReadOnly = true;
            dgvNZP.AddColumn("序号", "ID", 10);
            dgvNZP.AddColumn("工程名称", "MaterialName", 45);
            dgvNZP.AddColumn("剩余台数", "LeftCount", 45);
            dgvNZP.AddColumn("出发工程数", "TransportProjectCount", 45);

            dgvPX.AutoGenerateColumns = false;
            dgvPX.AllowUserToAddRows = false;
            dgvPX.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dgvPX.ReadOnly = true;
            dgvPX.AddColumn("序号", "ID", 10);
            dgvPX.AddColumn("工程名称", "MaterialName", 45);
            dgvPX.AddColumn("剩余台数", "LeftCount", 45);

            //拉绳灯
            dgvSL0.AutoGenerateColumns = false;
            dgvSL0.AllowUserToAddRows = false;
            dgvSL0.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dgvSL0.ReadOnly = true;
            dgvSL0.AddColumn("序号", "Id", 10);
            dgvSL0.AddColumn("工程名称", "PullingRopeName", 20);
            dgvSL0.AddColumn("拉绳", "PullShow", 20);
            dgvSL0.AddColumn("绿灯", "GreenShow", 25);
            dgvSL0.AddColumn("红灯", "RedShow", 25);

            dgvSL1.AutoGenerateColumns = false;
            dgvSL1.AllowUserToAddRows = false;
            dgvSL1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dgvSL1.ReadOnly = true;
            dgvSL1.AddColumn("序号", "Id", 10);
            dgvSL1.AddColumn("工程名称", "PullingRopeName", 20);
            dgvSL1.AddColumn("拉绳", "PullShow", 20);
            dgvSL1.AddColumn("绿灯", "GreenShow", 25);
            dgvSL1.AddColumn("红灯", "RedShow", 25);

            dgvSL2.AutoGenerateColumns = false;
            dgvSL2.AllowUserToAddRows = false;
            dgvSL2.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dgvSL2.ReadOnly = true;
            dgvSL2.AddColumn("序号", "Id", 10);
            dgvSL2.AddColumn("工程名称", "PullingRopeName", 20);
            dgvSL2.AddColumn("拉绳", "PullShow", 20);
            dgvSL2.AddColumn("绿灯", "GreenShow", 25);
            dgvSL2.AddColumn("红灯", "RedShow", 25);

            dgvSL3.AutoGenerateColumns = false;
            dgvSL3.AllowUserToAddRows = false;
            dgvSL3.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dgvSL3.ReadOnly = true;
            dgvSL3.AddColumn("序号", "Id", 10);
            dgvSL3.AddColumn("工程名称", "PullingRopeName", 20);
            dgvSL3.AddColumn("拉绳", "PullShow", 20);
            dgvSL3.AddColumn("绿灯", "GreenShow", 25);
            dgvSL3.AddColumn("红灯", "RedShow", 25);

            dgvSL4.AutoGenerateColumns = false;
            dgvSL4.AllowUserToAddRows = false;
            dgvSL4.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dgvSL4.ReadOnly = true;
            dgvSL4.AddColumn("序号", "Id", 10);
            dgvSL4.AddColumn("工程名称", "PullingRopeName", 20);
            dgvSL4.AddColumn("拉绳", "PullShow", 20);
            dgvSL4.AddColumn("绿灯", "GreenShow", 25);
            dgvSL4.AddColumn("红灯", "RedShow", 25);

            dgvSL5.AutoGenerateColumns = false;
            dgvSL5.AllowUserToAddRows = false;
            dgvSL5.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dgvSL5.ReadOnly = true;
            dgvSL5.AddColumn("序号", "Id", 10);
            dgvSL5.AddColumn("工程名称", "PullingRopeName", 20);
            dgvSL5.AddColumn("拉绳", "PullShow", 20);
            dgvSL5.AddColumn("绿灯", "GreenShow", 25);
            dgvSL5.AddColumn("红灯", "RedShow", 25);

            foreach (UnpackingDirectionShowModel model in GolbalVariable.UnpackingDirectionModelBag)
            {
                var control = this.tableLayoutPanel1.Controls.Find("labelPart" + model.TypeId, true);
                if (control != null && control.Length > 0)
                {
                    Label la = control[0] as Label;
                    la.Text = model.UnpackingName.ToString();
                }
            }

            DgvUpadte();
            //开启线程绑定数据
            cancel_KKStatuscontrol = new CancellationTokenSource();
            Task.Factory.StartNew(() =>
            {
                KKStatusCommand();
            }, cancel_KKStatuscontrol.Token);
        }

        private void DgvUpadte()
        {
            sysjUiUpdate();
            lsdUiUpdate();
        }

        private void FrmProgressDirection_SizeChanged(object sender, EventArgs e)
        {
            //asc.controllInitializeSize(this);
        }

        public void UpdateCells(UIDataGridView dgv)
        {
            if (dgv.Rows.Count > 0)
                dgv.Rows[0].Selected = false;

            foreach (DataGridViewRow item in dgv.Rows)
            {
                SignalLampShowModel model = item.DataBoundItem as SignalLampShowModel;
                if (model.IsPull == 1)
                    item.Cells["拉绳"].Style.BackColor = Color.Gray;
                else
                    item.Cells["拉绳"].Style.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(102)))));
                if (model.IsGreen == 1)
                    item.Cells["绿灯"].Style.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(176)))), ((int)(((byte)(80)))));
                else
                    item.Cells["绿灯"].Style.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(102)))));
                if (model.IsRed == 1)
                    item.Cells["红灯"].Style.BackColor = Color.Red;
                else
                    item.Cells["红灯"].Style.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(102)))));

            }
            //dgv.Update();
        }


        /// <summary>
        /// 开捆指示更新
        /// </summary>
        private async void KKStatusCommand()
        {
            while (!this.cancel_KKStatuscontrol.Token.IsCancellationRequested)
            {
                foreach (UnpackingDirectionShowModel model in GolbalVariable.UnpackingDirectionModelBag)
                {
                    UpdateUI(model);
                }
                await Task.Delay(1000);
            }
        }

        /// <summary>
        /// 更新数据
        /// </summary>
        private void UpdateUI(UnpackingDirectionShowModel unpackingDirectionModel)
        {
            try
            {
                if (this.labelrdcount.InvokeRequired)
                {
                    try
                    {
                        this.Invoke(new MethodInvoker(() =>
                        {
                            UpdateUIDATA(unpackingDirectionModel);
                        }));
                    }
                    catch (Exception ex)
                    {

                    }
                }
                else
                    UpdateUIDATA(unpackingDirectionModel);
            }
            catch (Exception ex)
            {

            }
        }

        /// <summary>
        /// 更新界面数据
        /// </summary>
        private void UpdateUIDATA(UnpackingDirectionShowModel unpackingDirectionModel)
        {
            var control = this.tableLayoutPanel1.Controls.Find(unpackingDirectionModel.ControlName, true);
            if (control != null && control.Length > 0)
            {
                Label la = control[0] as Label;
                la.Text = unpackingDirectionModel.UnpackingCount.ToString();
            }
        }

        /// <summary>
        /// 修改部品剩余数量输入框
        /// </summary>
        /// <param name="model">部品模型</param>
        private void materialDirectionEdit(MaterialDirectionModel model)
        {
            UIEditOption option = new UIEditOption();
            //UILocalize.OK = "保存";
            option.AutoLabelWidth = true;
            option.Text = "剩余台数修改(" + model.MaterialName + ")";
            option.AddInteger("LeftCount", "剩余台数", model.LeftCount, true);
            if(model.TypeId == 4)
            option.AddInteger("TransportProjectCount", "出发工程数", model.TransportProjectCount, true);

            UIEditForm frm = new UIEditForm(option);
            frm.ShowDialog();

            if (frm.IsOK)
            {
                model.LeftCount = int.Parse(frm["LeftCount"].ToString());
                if (model.TypeId == 4)
                    model.TransportProjectCount = int.Parse(frm["TransportProjectCount"].ToString());
                var result = bllMaterialDirection.Update(model);
                if(result.IsSuccess)
                {
                    UIMessageTip.ShowOk("修改成功");
                    LogObj.Info("修改剩余台数成功(" + model.MaterialName + ");作业者:" + ApplicationCache.CurrentUser.LoginName);
                }
                else
                {
                    UIMessageBox.ShowError("修改失败！");
                    LogObj.Error("修改剩余台数失败(" + model.MaterialName + ";"+ result.Dsca+ ");作业者:" + ApplicationCache.CurrentUser.LoginName);
                }
                sysjUiUpdate();
            }
            //UILocalize.OK = "确定";
            frm.Dispose();
        }

        /// <summary>
        /// 东面顺建双击列表事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvDMSY_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (ApplicationCache.CurrentUser.Permission == 0)
                materialDirectionEdit(dgvDMSY.CurrentRow.DataBoundItem as MaterialDirectionModel);
            else
                UIMessageBox.Show("该操作需要管理员权限，请先切换管理员账号！");

        }
        /// <summary>
        /// 西面顺建双击列表事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvXMSY_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (ApplicationCache.CurrentUser.Permission == 0)
                materialDirectionEdit(dgvXMSY.CurrentRow.DataBoundItem as MaterialDirectionModel);
            else
                UIMessageBox.Show("该操作需要管理员权限，请先切换管理员账号！");
        }
        /// <summary>
        /// 中物顺建双击列表事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvZWSJ_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (ApplicationCache.CurrentUser.Permission == 0)
                materialDirectionEdit(dgvZWSJ.CurrentRow.DataBoundItem as MaterialDirectionModel);
            else
                UIMessageBox.Show("该操作需要管理员权限，请先切换管理员账号！");
        }
        /// <summary>
        /// 内制品双击列表事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvNZP_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (ApplicationCache.CurrentUser.Permission == 0)
                materialDirectionEdit(dgvNZP.CurrentRow.DataBoundItem as MaterialDirectionModel);
            else
                UIMessageBox.Show("该操作需要管理员权限，请先切换管理员账号！");
        }
        /// <summary>
        /// 排序工程双击列表事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvPX_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (ApplicationCache.CurrentUser.Permission == 0)
                materialDirectionEdit(dgvPX.CurrentRow.DataBoundItem as MaterialDirectionModel);
            else
                UIMessageBox.Show("该操作需要管理员权限，请先切换管理员账号！");
        }

        private void sysjUiUpdate_event()
        {
            sysjUiUpdate();
        }

        private void lsdUiUpdate_event()
        {
            lsdUiUpdate();
        }

        private void sysjUiUpdate()
        {
            this.Invoke(new MethodInvoker(() =>
            {
                dgvDMSY.DataSource = null;
                dgvDMSY.DataSource = GolbalVariable.MaterialDirectionBag.Where(x => x.TypeId == 1).OrderBy(x => x.ID).ToList();
                dgvXMSY.DataSource = null;
                dgvXMSY.DataSource = GolbalVariable.MaterialDirectionBag.Where(x => x.TypeId == 2).OrderBy(x => x.ID).ToList();
                dgvZWSJ.DataSource = null;
                dgvZWSJ.DataSource = GolbalVariable.MaterialDirectionBag.Where(x => x.TypeId == 3).OrderBy(x => x.ID).ToList();
                dgvNZP.DataSource = null;
                dgvNZP.DataSource = GolbalVariable.MaterialDirectionBag.Where(x => x.TypeId == 4).OrderBy(x => x.ID).ToList();
                dgvPX.DataSource = null;
                dgvPX.DataSource = GolbalVariable.MaterialDirectionBag.Where(x => x.TypeId == 5).OrderBy(x => x.ID).ToList();
            }));
        }

        private void lsdUiUpdate()
        {
            this.Invoke(new MethodInvoker(() =>
            {
                dgvSL0.DataSource = null;
                dgvSL0.DataSource = GolbalVariable.SignalLampShowModelBag.Where(x => x.TypeId == 0).OrderBy(x => x.Id).ToList();
                dgvSL1.DataSource = null;
                dgvSL1.DataSource = GolbalVariable.SignalLampShowModelBag.Where(x => x.TypeId == 1).OrderBy(x => x.Id).ToList();
                dgvSL2.DataSource = null;
                dgvSL2.DataSource = GolbalVariable.SignalLampShowModelBag.Where(x => x.TypeId == 2).OrderBy(x => x.Id).ToList();
                dgvSL3.DataSource = null;
                dgvSL3.DataSource = GolbalVariable.SignalLampShowModelBag.Where(x => x.TypeId == 3).OrderBy(x => x.Id).ToList();
                dgvSL4.DataSource = null;
                dgvSL4.DataSource = GolbalVariable.SignalLampShowModelBag.Where(x => x.TypeId == 4).OrderBy(x => x.Id).ToList();
                dgvSL5.DataSource = null;
                dgvSL5.DataSource = GolbalVariable.SignalLampShowModelBag.Where(x => x.TypeId == 5).OrderBy(x => x.Id).ToList();
                
                UpdateCells(dgvSL0);
                UpdateCells(dgvSL1);
                UpdateCells(dgvSL2);
                UpdateCells(dgvSL3);
                UpdateCells(dgvSL4);
                UpdateCells(dgvSL5);
            }));
        }

        private void FrmProgressDirection_FormClosing(object sender, FormClosingEventArgs e)
        {
            logisticsAndongHandler.ResetSignalLamp();
            try
            {
                //foreach (var cd in GolbalVariable.SignalLampBlinkThreadDictionary)
                //{
                //    var thread = cd.Value;
                //    if (GolbalVariable.SignalLampBlinkThreadDictionary.TryRemove(cd.Key, out thread))
                //    {
                //        thread.Abort();
                //    }
                //}
                cancel_KKStatuscontrol.Cancel();
                logisticsAndongHandler.cancel_mainequip.Cancel();
            }catch(Exception ex)
            {
            }

        }

        private void FrmProgressDirection_FormClosed(object sender, FormClosedEventArgs e)
        {
        }

        private void uiButton1_Click(object sender, EventArgs e)
        {
            logisticsAndongHandler.StartBlink(uiTextBox1.Text.Trim());
        }

        private void uiButton2_Click(object sender, EventArgs e)
        {
            logisticsAndongHandler.StopBlink(uiTextBox1.Text.Trim());
        }

        private void uiButton3_Click(object sender, EventArgs e)
        {
            logisticsAndongHandler.StartBlinkAll();
        }

        private void uiButton4_Click(object sender, EventArgs e)
        {
            logisticsAndongHandler.StopBlinkAll();
        }

        private void uiButton6_Click(object sender, EventArgs e)
        {
            logisticsAndongHandler.GreenOpenAll();
        }

        private void uiButton5_Click(object sender, EventArgs e)
        {
            logisticsAndongHandler.StartBlinkAndRedOpenAll();
        }
    }
}
